<?php
namespace App\Services;

use App\Models\YikaoMajors;
use App\Models\YikaoSpecialMajor;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class SpecialMajorSpiderService
{
    private $client;
    private $logger;
    private $proxy_enable = false;

    private $timeout = 10;

    public function __construct(bool $proxy_enable = false)
    {
        $this->client = new Client([
            'timeout' => $this->timeout,
            'headers' => [
                'Referer' => 'https://www.gaokao.cn/',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            ]
        ]);


        // 确保logs目录存在
        $logDir = dirname(__DIR__, 2).'/storage/logs';
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }

        $this->logger = new Logger('special-major-spider');
        $this->logger->pushHandler(new StreamHandler($logDir.'/special-major-spider.log'));
        $this->proxy_enable = $proxy_enable;
    }

    /**
     * @throws GuzzleException
     */
    public function fetchPage($level1, $level2, int $page = 1, int $size = 30): array
    {
        try {
            $payload = [
                'keyword' => '',
                'level1' => $level1,
                'level2' => $level2,
                'level3' => '',
                'page' => $page,
                'signsafe' => 'ccbe4b766367d46503c12d2b3ce183cf',
                'size' => $size,
                'sort' => '',
                'uri' => 'apidata/api/gkv3/special/lists'
            ];

            $options = [
                'query' => $payload,
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'json' => $payload
            ];

            if ($this->proxy_enable) {
                $options['proxy'] = 'http://127.0.0.1:1080';
            }

            try {
                $response = $this->client->post('https://api.zjzw.cn/web/api/', $options);
            } catch (GuzzleException $e) {
                $this->logger->error("请求失败: " . $e->getMessage());
                throw $e;
            }

            $data = json_decode($response->getBody(), true);

            if ($data['code'] !== '0000') {
                throw new \Exception("API返回错误: {$data['message']}");
            }
            echo "第 {$page} 页数据: " . json_encode($data['data']) . "\n";
            return $data['data'];

        } catch (RequestException $e) {
            $this->logger->error("请求失败: " . $e->getMessage());
            throw $e;
        }
    }

    public function saveData(array $items): int
    {
        $count = 0;
        foreach ($items as $item) {
            try {
                $data = [
                    'p_id' => $item['id'] ?? '',
                    'boy_rate' => $item['boy_rate'] ?? '',
                    'degree' => $item['degree'] ?? '',
                    'fivesalaryavg' => $item['fivesalaryavg'] ?? '',
                    'girl_rate' => $item['girl_rate'] ?? '',
                    'hightitle' => $item['hightitle'] ?? '',
                    'level1' => $item['level1'] ?? '',
                    'level1_name' => $item['level1_name'] ?? '',
                    'level2' => $item['level2'] ?? '',
                    'level2_name' => $item['level2_name'] ?? '',
                    'level3' => $item['level3'] ?? '',
                    'level3_name' => $item['level3_name'] ?? '',
                    'limit_year' => $item['limit_year'] ?? '',
                    'name' => $item['name'] ?? '',
                    'rank' => $item['rank'] ?? '',
                    'salaryavg' => $item['salaryavg'] ?? '',
                    'spcode' => $item['spcode'] ?? '',
                    'special_id' => $item['special_id'] ?? 0
                ];
                YikaoMajors::query()->updateOrCreate(
                    ['p_id' => $data['p_id']],
                    $data
                );
                $count++;
            } catch (\Exception $e) {
                $this->logger->error("保存数据失败: " . $e->getMessage(), ['item' => $item]);
            }
        }
        return $count;
    }
}
